import { MessageBar, MessageBarType, PrimaryButton, TextField } from "@fluentui/react";
import { useEffect, useState } from "react";
import { isValidLocalPath } from "../utils";
import { open } from '@tauri-apps/api/dialog';
import { documentDir } from '@tauri-apps/api/path';
import { path } from "@tauri-apps/api";
import { RS, useITranslation } from "../../i18n/config";
import { tk } from "../../i18n/config";

interface IProps {
    label: string;
    defaultPath: string;
}
function usePluginInstallPath(props: IProps) {
    useEffect(() => {
        documentDir().then(_path => {
            path.join(_path, props.defaultPath).then(v => {
                setInstallPath(v);
            })
        });

    }, [])
    const selectInstallPath = () => {
        open({
            directory: true,
            multiple: false
        }).then((directory) => {
            if (directory) {
                var dir = typeof directory === 'string' ? directory : directory[0];
                setInstallPath(dir + '\\');
            }
        });
    }
    const { t } = useITranslation();
    const [installPath, setInstallPath] = useState("");
    const installPathValid = installPath.length > 0 && isValidLocalPath(installPath);

    const installPathWithSlash = installPath.lastIndexOf('\\') === installPath.length - 1 ? installPath : installPath + '\\'
    const isEnglish = isEnglishPath(installPathWithSlash);
    const dom = <>
        <div style={{ display: 'flex', justifyContent: 'stretch', alignItems: 'flex-start', width: "100%" }}>
            <TextField
                maxLength={150}
                className="installPath"
                label={t(tk.Save_to_Folder, { a: props.label })}
                errorMessage={installPathValid ? undefined : RS.Path_Not_Valid}
                required
                value={installPath}
                onChange={ev => setInstallPath((ev.target as HTMLInputElement).value)} />
            <PrimaryButton style={{ width: '24px', marginLeft: '8px', marginTop: '34px' }} onClick={selectInstallPath}>{RS.Select}</PrimaryButton>
        </div>

        {isEnglish ? undefined : <MessageBar
            messageBarType={MessageBarType.warning}
            isMultiline={true}
        >
            <span>{RS.None_En_Path_Warn_A}</span>
            <span>{RS.None_En_Path_Warn_B}</span>
        </MessageBar>}
    </>
    return [dom, installPathWithSlash, installPathValid] as const;
}
export default usePluginInstallPath;

function isEnglishPath(path: string) {
    const regex = /^[a-zA-Z\s\\\/:.-]+$/;
    return regex.test(path);
}